// pages/handle/handle.js// pages/details/details.js
import {
  rejectedAdvise,
  sentAddress
} from "../../apis/release_api"
import {
  getFirstAddress,
  getSecondAddress,
}
from "../../apis/address_api"
import {
  uploadResults,
  getResultsByAdviseId
} from "../../apis/results_api"
// 上传图片路径
const uploadImgBaseUrl = getApp().globalData.uploadImgBaseUrl;

Page({
  /**
   * 页面的初始数据
   */
  data: {
    watermarkText: wx.getStorageSync("name") + wx.getStorageSync("phoneNumber").slice(-4),
    // 用户权限代码
    code: '',
    // 一级权限代码
    firstCode: getApp().globalData.firstCode,
    // 建议
    advise: {},
    // 一级辖区位置
    firstAddress: "",
    // 二级辖区位置
    secondAddress: "",
    // 辖区位置列表
    locationList: [
      [],
      []
    ],
    // 最后处理结果
    results: {},
    // 处理结果
    content: '',
    // 图片列表
    imageList: [],
    // 是否能选择图片
    isSelectPhoto: true,
    isAdmin:false
  },
  userData: {
    // 用户手机号
    phone: '',
    // 用户姓名
    name: "",
    // 选择图片数量
    maxImgNum: 3,
  },

  //空方法，去除警告，不可删除
  onInput() {
    // 空方法，去除警告，不可删除
  },
  copyText: function () {
    var content = this.data.advise.content;
    wx.setClipboardData({
      data: content,
      success: function () {
        wx.showToast({
          title: '已复制',
          icon: 'success',
          duration: 1000
        });
      }
    });
  },
  //上传图片
  uploadImage() {
    // 还能再选几张图片
    let imageList = this.data.imageList
    let max = this.userData.maxImgNum - imageList.length
    wx.chooseImage({
      count: max,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        let tempFilePaths = res.tempFilePaths
        tempFilePaths.forEach(item => {
          wx.uploadFile({
            filePath: item,
            name: 'file',
            url: uploadImgBaseUrl + '/upload/localhost',
            header: {
              "Content-Type": "multipart/form-data"
            },
            success: res => {
              let url = JSON.parse(res.data).data
              let imageList = this.data.imageList.concat(url)
              max = this.userData.maxImgNum - imageList.length
              let isSelectPhoto = max <= 0 ? false : true
              this.setData({
                imageList: imageList,
                isSelectPhoto: isSelectPhoto
              })
            }
          })
        })
      }
    })
  },

  //显示全屏图片
  showImage(e) {
    let imageList = []
    e.target.dataset.imagelist.forEach(item => {
      imageList.push({
        url: item.url ? item.url : item,
      })
    })
    wx.previewMedia({
      sources: imageList,
      current: e.target.dataset.index
    })
  },

  //删除图片
  onDelImage(event) {
    let imageList = this.data.imageList
    imageList.splice(event.target.dataset.index, 1)
    this.setData({
      imageList: imageList
    })
    if (imageList.length < this.userData.maxImgNum) {
      this.setData({
        isSelectPhoto: true
      })
    }
  },

  // 发送处理
  sendResults() {
    
    let adviseId = this.data.advise.id
    let content = this.data.content
    let phone = this.userData.phone
    let name = this.userData.name
    let imgList = this.data.imageList
    if (content.trim() === '') {
      wx.showModal({
        title: '请输入内容后方可完成上传',
      })
      return;
    }
    if (imgList.length ==0) {
      wx.showModal({
        title: '请上传图片可完成上传',
      })
      return;
    }
    uploadResults(adviseId, content, phone, name, imgList).then(res => {
      if (res.success) {
        wx.showToast({
          title: '处理成功',
          icon: 'success',
          duration: 2000
        })
        this.setData({
          content: '',
          imageList: [],
          isSelectPhoto: true,
        })
        // 刷新上一个页面数据并跳转
        let pages = getCurrentPages();
        let releaseList = pages[pages.length - 2];
        releaseList.onPullDownRefresh()
        wx.navigateBack({
          delta: 1
        })
      } else {
        wx.showToast({
          title: res.message,
          icon: 'error',
          duration: 2000
        })
      }
    })
  },

  //发送分配
  sentAddress() {
    let id = this.data.advise.id
    let firstAddress = this.data.firstAddress
    let secondAddress = this.data.secondAddress
    if (secondAddress == this.data.advise.secondAddress) {
      wx.showModal({
        title: '请选择分配辖区',
      })
      return;
    }
    wx.showModal({
      title: '提示',
      content: '确认分配于' + firstAddress + "/" + secondAddress,
      success: res => {
        if (res.confirm) {
          sentAddress(id, firstAddress, secondAddress).then(res => {
            if (res.success) {
              wx.showToast({
                title: '分配成功',
                icon: 'success',
                duration: 2000
              })
              // 刷新上一个页面数据并跳转
              let pages = getCurrentPages();
              let releaseList = pages[pages.length - 2];
              releaseList.onPullDownRefresh()
              wx.navigateBack({
                delta: 1
              })
            } else {
              wx.showToast({
                title: res.message,
                icon: 'error',
                duration: 2000
              })
            }
          })
        }
      }
    })
  },

  //误报驳回
  rejected() {
    let id = this.data.advise.id
    wx.showModal({
      title: '提示',
      content: '确认是否误报驳回？',
      success: res => {
        if (res.confirm) {
          rejectedAdvise(id).then(res => {
            if (res.success) {
              wx.showToast({
                title: '驳回成功',
                icon: 'success',
                duration: 2000
              })
              // 刷新上一个页面数据并跳转
              let pages = getCurrentPages();
              let releaseList = pages[pages.length - 2];
              releaseList.onPullDownRefresh()
              wx.navigateBack({
                delta: 1
              })
            } else {
              wx.showToast({
                title: res.message,
                icon: 'error',
                duration: 2000
              })
            }
          })
        }
      }
    })
  },

  // 获取用户信息
  getUserInfo() {
    let code = wx.getStorageSync("code")
    let firstCode = getApp().globalData.firstCode
    if (code == firstCode) {
      this.getFirstAddress()
      this.getSecondAddress(1)
    }
    let phone = wx.getStorageSync('phoneNumber')
    let name = wx.getStorageSync('name')
    this.userData.phone = phone
    this.userData.name = name
    let adminPhoneList = getApp().globalData.adminPhoneList
    this.setData({
      code: code,
      isAdmin:adminPhoneList.indexOf(phone)>=0
    })
  },

  // 获取建议和驳回理由
  getAdvise(id) {
    getResultsByAdviseId(id).then(res => {
      let advise = res.data.advise
      let resultsList = res.data.resultsList
      wx.setNavigationBarTitle({
        title: advise.stateCode == 0 ? '待分配' : '待处理',
      })
      let results = {}
      if (resultsList.length > 0) {
        results = resultsList[resultsList.length - 1]
      }
      this.setData({
        firstAddress: advise.firstAddress,
        secondAddress: advise.secondAddress,
        advise,
        results
      })
    })
  },

  //获取辖区位置
  getAddress(e) {
    let locationList = this.data.locationList
    this.setData({
      firstAddress: locationList[0][e.detail.value[0]].address,
      secondAddress: locationList[1][e.detail.value[1]].address
    })
  },

  //更新二级辖区列表
  updateSecondAddress(e) {
    if (e.detail.column == 0) {
      let id = this.data.locationList[0][e.detail.value].id
      this.getSecondAddress(id)
    }
  },

  //获取一级辖区列表
  getFirstAddress() {
    getFirstAddress().then(res => {
      this.setData({
        'locationList[0]': res.data
      })
    })
  },

  //获取二级辖区列表
  getSecondAddress(id) {
    getSecondAddress(id).then(res => {
      this.setData({
        'locationList[1]': res.data,
      });
    })
  },

  // 初始化页面数据
  getPageData(id) {
    this.getUserInfo()
    this.getAdvise(id)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getPageData(options.id)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})